package controllers.listeners.lexicon;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.JTextField;

import models.LexiconModel;

import objects.Feature;
import objects.FeatureList;
import objects.Lexicon;
import objects.LexiconList;
import objects.Stem;

import views.ViewLexicon;

/* Adds a feature to the stem */
/* actionPerformed when you click the "Add Feature" button */
public class AddFeatureActionListener implements ActionListener {
	
	private ViewLexicon view;
	
	public AddFeatureActionListener() {}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		Lexicon lexicon = LexiconModel.getLexicon();
		String inputName = null;
		String inputValues = null;
		
		try {
			do {
				JTextField featureName = new JTextField();
				JTextField featureValues = new JTextField();
				
				Object[] message = {
				    "Feature Name: ", featureName,
				    "Feature Values(separate through a comma(,):", featureValues
				};
				int returnType = JOptionPane.showConfirmDialog(view, message, "New Feature", JOptionPane.OK_CANCEL_OPTION);
				
				inputName = featureName.getText();
				inputValues = featureValues.getText();
				
				inputName = inputName.trim();
				inputValues = inputValues.trim();
				
				if (returnType != JOptionPane.OK_OPTION) {
					return;
				}
				
				if (inputName.equals("") && inputValues.equals("")) {
					JOptionPane.showMessageDialog(view, "Please complete the fields!", "Error", JOptionPane.ERROR_MESSAGE);
				}
			}
			while (inputName.equals(""));
			
			FeatureList newFeature = new FeatureList();				    	
	    	newFeature.setName(inputName);
	    	
	    	String[] lstInputValues = inputValues.split("\\s*,\\s*");
	    	
	    	for (String feature : lstInputValues) {
	    		newFeature.addValuesItem(feature);
	    	}
	    	
	    	for (LexiconList currentLexiconList : lexicon.getLexiconList()) {
	    		if (view.getSelectedCategory().equals(currentLexiconList.getLabel())) {
	    			currentLexiconList.addFeatureListItem(newFeature);
					
					for (Stem currentStem : currentLexiconList.getStemList()) {
				    	Feature stemFeature = new Feature();
				    	stemFeature.setName(inputName);
				    	stemFeature.setValue(lstInputValues[0]);	
						currentStem.addFeatureListItem(stemFeature);
					}
					
					view.refreshTable();
					break;
	    		}
	    	}
		}
		catch(Exception ex) {}
	}
	
	public void setView(ViewLexicon view) {
		this.view = view;
	}
	
}
